//
//  Base.m
//  IHKApp
//
//  Created by calvin on 15/4/7.
//  Copyright (c) 2015年 www.ihk.cn. All rights reserved.
//

#import "Base.h"
#import <CommonCrypto/CommonDigest.h>
@implementation Base


+ (void)getData:(NSString *)serverUrl useParameters:(NSMutableDictionary *)paras success:(void (^)(NSDictionary *dic))success fail:(void (^)(NSError *error))fail {

    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer = [AFHTTPResponseSerializer serializer];
    session.requestSerializer.timeoutInterval = 30;
    
    [self showRequestUrl:serverUrl paras:paras];//输出
    
    [session GET:serverUrl parameters:paras progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
            success(result);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (fail) {
            fail(error);
        }
    }];
}



+ (void)postData:(NSString *)serverUrl useParameters:(NSMutableDictionary *)paras success:(void (^)(NSDictionary *result))success fail:(void (^)(NSError *error))fail {
    

    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer = [AFHTTPResponseSerializer serializer];
    session.requestSerializer.timeoutInterval = 30;
    [self showRequestUrl:serverUrl paras:paras];//输出

    [session POST:serverUrl parameters:paras constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        success(result);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        fail(error);
    }];
}









/***********************************                   **********************/

+ (NSString *)getKey {
    
    NSDate *thisDate = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *strDate = [dateFormatter stringFromDate:thisDate];
    NSString *sign = [NSString stringWithFormat:@"ihkapp_web%@", strDate] ;
    NSString *str = [Base getmd5:sign];
    return str;
}
+(NSString *)getmd5:(NSString *)str
{
    //DONE:md5加密
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

+ (void)postDataWithUrl:(NSString *)serverUrl
              withParas:(NSMutableDictionary *)paras
               withData:(NSData *)data
               progress:(void (^)(float currentProgress))progress
                success:(void (^)(NSDictionary *result))success
                   fail:(void (^)(NSError *error))fail {
    
    [paras setValue:[Base getKey] forKey:@"ukey"];
    [paras setValue:@"IOS" forKey:@"appType"];
    NSDictionary *infoDic = [[NSBundle mainBundle]infoDictionary];
    [paras setValue:[infoDic objectForKey:@"CFBundleShortVersionString"] forKey:@"appVersion"];
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer = [AFHTTPResponseSerializer serializer];
    session.requestSerializer.timeoutInterval = 60;
    
    [session POST:serverUrl parameters:paras constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if (data) {
            [formData appendPartWithFileData:data name:@"imageFile" fileName:@"imageFile.jpg" mimeType:@"image/jpeg"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        progress((float)1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        success(result);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        fail(error);
    }];
}

+ (void)postDataWithUrlAndImageArray:(NSString *)serverUrl
                           withParas:(NSMutableDictionary *)paras
                          imageArray:(NSArray *)imageArray
                            progress:(void (^)(float currentProgress))progress
                             success:(void (^)(NSDictionary *result))success
                                fail:(void (^)(NSError *error))fail {
    
    [paras setValue:[Base getKey] forKey:@"ukey"];
    [paras setValue:@"IOS" forKey:@"appType"];
    NSDictionary *infoDic = [[NSBundle mainBundle]infoDictionary];
    [paras setValue:[infoDic objectForKey:@"CFBundleShortVersionString"] forKey:@"appVersion"];

    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer = [AFHTTPResponseSerializer serializer];
    session.requestSerializer.timeoutInterval = 100;
    
    [self showRequestUrl:serverUrl paras:paras];//输出

    [session POST:serverUrl parameters:paras constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        for (int i = 0; i < imageArray.count; i++) {
            
            NSData *data = (NSData *)imageArray[i];
            if (data) {
                [formData appendPartWithFileData:data name:[NSString stringWithFormat:@"imageFileList%d", i+1] fileName:[NSString stringWithFormat:@"imageFileList%d.jpg", i+1] mimeType:@"image/jpeg"];
            }
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        progress((float)1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        success(result);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        fail(error);
    }];
}

+ (void)postVideoWithUrl:(NSString *)serverUrl
               withParas:(NSMutableDictionary *)paras
                withData:(NSData *)data
                progress:(void (^)(float currentProgress))progress
                 success:(void (^)(NSDictionary *result))success
                    fail:(void (^)(NSError *error))fail {
    
    [paras setValue:[Base getKey] forKey:@"ukey"];
    [paras setValue:@"IOS" forKey:@"appType"];
    NSDictionary *infoDic = [[NSBundle mainBundle]infoDictionary];
    [paras setValue:[infoDic objectForKey:@"CFBundleShortVersionString"] forKey:@"appVersion"];

    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer = [AFHTTPResponseSerializer serializer];
    session.requestSerializer.timeoutInterval = 3600;
    
    [session POST:serverUrl parameters:paras constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if (data) {
            [formData appendPartWithFileData:data name:@"videoName" fileName:@"video.mp4" mimeType:@"video/mpeg4"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        progress((float)1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        success(result);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        fail(error);
    }];
}

+ (void)postVideoWithUrl:(NSString *)serverUrl
               withParas:(NSMutableDictionary *)paras
           withVideoData:(NSData *)videoData
           withImageData:(NSData *)imageData
                progress:(void (^)(float currentProgress))progress
                 success:(void (^)(NSDictionary *result))success
                    fail:(void (^)(NSError *error))fail {
    
    [paras setValue:[Base getKey] forKey:@"ukey"];
    [paras setValue:@"IOS" forKey:@"appType"];
    NSDictionary *infoDic = [[NSBundle mainBundle]infoDictionary];
    [paras setValue:[infoDic objectForKey:@"CFBundleShortVersionString"] forKey:@"appVersion"];
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer = [AFHTTPResponseSerializer serializer];
    session.requestSerializer.timeoutInterval = 3600;
    
    [session POST:serverUrl parameters:paras constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        if (videoData) {
            [formData appendPartWithFileData:videoData name:@"videoName" fileName:@"video.mp4" mimeType:@"video/mpeg4"];
        }
        if (imageData) {
            [formData appendPartWithFileData:imageData name:@"picName" fileName:@"image.jpg" mimeType:@"image/jpeg"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        progress((float)1.0 * uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        success(result);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        fail(error);
    }];
}


+ (void)showRequestUrl:(NSString *)serverUrl paras:(NSMutableDictionary *)paras {
    NSString *url = @"";
    for (NSString *keyName in paras) {
        url = [[[[url stringByAppendingString:@"&"] stringByAppendingString:keyName]stringByAppendingString:@"="]stringByAppendingString:[NSString stringWithFormat:@"%@",[paras objectForKey:keyName]]];
    }
    url = [url substringFromIndex:1];
    url = [[serverUrl stringByAppendingString:@"?"]stringByAppendingString:url];
    NSLog(@"requestUrl:%@",url);
}

@end
